<template>
  <div class="app-container">
    <template v-if="showPage == true">
      <div class="search-bar">
        <el-form ref="formRef" :model="usageForm" label-width="auto" :inline="true">
          <el-form-item label="关键字">
            <el-input v-model="usageForm.keywords" placeholder="房屋信息/业主名" clearable />
          </el-form-item>
          <el-form-item label="券码">
            <el-input v-model="usageForm.coupon" placeholder="券码" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <enum-select
              clearable
              v-model="usageForm.statuses"
              placeholder="请选择状态"
              :enums="USAGE_STATUS"
            ></enum-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <Search />
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon>
                <Refresh />
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-dialog v-model="dialogVisible" title="上传" width="500" :before-close="handleClose">
        <div>
          <el-form ref="formPut" :rules="rules" :model="couponInfo" label-width="auto">
            <el-form-item label="开工/安装时间" prop="operationStartTime">
              <el-date-picker
                v-model="couponInfo.operationStartTime"
                type="datetime"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD hh:mm:ss"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="上传成果" prop="file">
              <MultiImageUpload v-model="couponInfo.file" :showTip="false" :limit="5" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="sbumit">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <BasePageTable
        :table-data="tableData"
        :table-columns-data="tableColumnsData"
        :total="total"
        :loading="loading"
        :page-num="usageForm.pageNum"
        :page-size="usageForm.pageSize"
        @handleQuery="changePage"
      >
        <template #index="scoped">
          {{ scoped.index + 1 }}
        </template>
        <template #file="{ row }">
          <MultiImageUpload
            v-model="row.files"
            disabled
            :showTip="false"
            :limit="row.files ? 1 : 0"
          />
        </template>
        <template #status="{ row }">
          <el-tag :type="couponStatusMap[row.status] || 'primary'">
            {{ getLabelByValue(USAGE_STATUS, row.status) }}
          </el-tag>
        </template>
        <template #couponCode="{ row }">
          {{ showCodeList(row.coupons) }}
        </template>
        <template #operation="{ row }">
          <el-button
            link
            type="primary"
            @click="handleEdit(row, 'put')"
            :disabled="row.status == 2 || row.status == 3 || row.status == 5"
          >
            上传
          </el-button>
          <el-button link type="primary" @click="handleEdit(row, 'look')">查看详情</el-button>
        </template>
      </BasePageTable>
    </template>
    <template v-else>
      <couponForm @backTo="BackTo" :couponArticle="couponData"></couponForm>
    </template>
  </div>
</template>
<script setup>
import { USAGE_STATUS } from "@/enums/coupon/coupon-usage";
import couponApi from "@/api/coupon/coupon";
import couponForm from "../components/couponForm/index.vue";
import { getLabelByValue, getLabelValueList } from "@/utils/enums";

const { proxy } = getCurrentInstance();
const usageForm = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  coupon: "",
  statuses: "",
  redemptionBeginTime: "",
  redemptionEndTime: "",
});

const total = ref();

const couponStatusMap = {
  [USAGE_STATUS.PASS.value]: "success",
  [USAGE_STATUS.REJECTED.value]: "success",
  [USAGE_STATUS.APPROVED.value]: "danger",
  [USAGE_STATUS.NOT_FILLED.value]: "info",
  [USAGE_STATUS.FILLED.value]: "info",
};

const couponInfo = ref({
  id: undefined,
  houseId: undefined,
  linkType: undefined,
  linkId: undefined,
  operationStartTime: "",
  file: [],
});
const couponData = ref();
const dialogVisible = ref(false);
const showPage = ref(true);
const tableData = ref([]);
const loading = ref(false);
const tableColumnsData = ref([
  {
    prop: "index",
    label: "序号",
    showOverflowTooltip: true,
    customSlot: "index",
  },
  {
    prop: "houseNeighborhood",
    label: "小区信息",
    showOverflowTooltip: true,
  },
  {
    prop: "houseNumber",
    label: "门牌号",
    showOverflowTooltip: true,
  },
  {
    prop: "ownName",
    label: "业主名",
    showOverflowTooltip: true,
  },
  {
    prop: "linkContractTime",
    label: "签约时间",
    showOverflowTooltip: true,
  },
  {
    prop: "categoryName",
    label: "品类",
    showOverflowTooltip: true,
  },
  {
    prop: "coupons.couponCode",
    label: "代金券券码",
    showOverflowTooltip: true,
    customSlot: "couponCode",
  },
  {
    prop: "totalCoins",
    label: "核销总积分",
    showOverflowTooltip: true,
  },
  {
    prop: "status",
    label: "状态",
    showOverflowTooltip: true,
    customSlot: "status",
  },
  {
    prop: "operationStartTime",
    label: "开工时间",
    showOverflowTooltip: true,
  },
  // {
  //   prop: "file",
  //   label: "成果展示",
  //   showOverflowTooltip: true,
  //   customSlot: "file",
  //   width: 200,
  // },
  {
    prop: "operation",
    label: "操作",
    width: 200,
    align: "center",
    fixed: "right",
    customSlot: "operation", // 自定义插槽名称
  },
]);

const rules = ref({
  operationStartTime: [{ required: true, message: "请确认开工时间", trigger: "change" }],
  file: [{ required: true, message: "请上传成果", trigger: "change" }],
});

function handleSearch() {
  usageForm.pageNum = 1;
  getList();
}
function changePage(val) {
  usageForm.pageNum = val.pageNum;
  usageForm.pageSize = val.pageSize;
  getList();
}
// 重置查询
function handleResetQuery() {
  usageForm.statuses = "";
  usageForm.pageNum = 1;
  usageForm.keywords = "";
  usageForm.coupon = "";
  usageForm.redemptionBeginTime = "";
  usageForm.redemptionEndTime = "";
  getList();
}

// 关闭上传
function handleClose() {
  dialogVisible.value = false;
  couponInfo.value.id = undefined;
  couponInfo.value.houseId = undefined;
  couponInfo.value.linkType = undefined;
  couponInfo.value.linkId = undefined;
  couponInfo.value.file = [];
  couponInfo.value.operationStartTime = "";
}

function getList() {
  loading.value = true;
  try {
    couponApi
      .getPage(usageForm)
      .then((res) => {
        tableData.value = res.list;
        total.value = res.total;
        for (let i = 0; i < tableData.value.length; i++) {
          tableData.value[i].files = JSON.parse(tableData.value[i].file);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  } catch {}
}

function showCodeList(data) {
  if (data) {
    let names = data.map((item) => item.couponCode);
    return names.join(",");
  } else {
    return "";
  }
}

function handleEdit(row, type) {
  if (type == "put") {
    couponInfo.value.id = row.id;
    couponInfo.value.houseId = row.houseId;
    couponInfo.value.linkType = row.linkType;
    couponInfo.value.linkId = row.linkId;
    dialogVisible.value = true;
  } else if (type == "look") {
    showPage.value = false;
    couponData.value = row;
  }
}

function sbumit() {
  proxy.$refs["formPut"].validate(async (valid) => {
    if (valid) {
      loading.value = true;
      let data = JSON.parse(JSON.stringify(couponInfo.value));
      data.file = JSON.stringify(data.file);
      try {
        couponApi
          .putAchievement(data)
          .then((res) => {
            getList();
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      } catch {}
    }
  });
}

function BackTo() {
  showPage.value = true;
  getList();
}

onMounted(async () => {
  getList();
});
</script>
